import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Response, Request } from 'express';

export interface ErrorResponse {
  code: number;
  message: string;
  timestamp: string;
  path: string;
}

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    let status = HttpStatus.INTERNAL_SERVER_ERROR; // 默认 500
    let message = '服务器内部错误';
    if (exception instanceof HttpException) {
      status = exception.getStatus();
      const exceptionResponse = exception.getResponse();
      message =
        typeof exceptionResponse === 'string'
          ? exceptionResponse
          : (exceptionResponse as any).message || message;
    }
    else if (exception instanceof Error) {
      message = exception.message;
    }
    const errorResponse: ErrorResponse = {
      code: status,
      message: message,
      timestamp: new Date().toISOString(),
      path: request.url,
    };
    response.status(status).json({
      code: errorResponse.code,
      message: errorResponse.message,
      data: null, // 错误时没有数据
      timestamp: errorResponse.timestamp,
      path: errorResponse.path,
    });
  }
}